<?php
// POST 请求
function http_post($url,$param){
	$oCurl = curl_init();
	if(stripos($url,"https://")!==FALSE){
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($oCurl, CURLOPT_SSLVERSION, 1);
	}
	if (is_string($param)) {
		$strPOST = $param;
	} else {
		$strPOST=http_build_query($param);
	}
	curl_setopt($oCurl, CURLOPT_URL, $url);
	curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt($oCurl, CURLOPT_POST,true);
	curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
	$sContent = curl_exec($oCurl);
	$aStatus = curl_getinfo($oCurl);
	curl_close($oCurl);
	
	//echo $aStatus["http_code"];
	if(intval($aStatus["http_code"])==200){
		return $sContent;
	}else{
		return false;
	}
}
// GET 请求
function http_get($url){
	$oCurl = curl_init();
	if(stripos($url,"https://")!==FALSE){
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
	}
	curl_setopt($oCurl, CURLOPT_URL, $url);
	curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
	$sContent = curl_exec($oCurl);
	$aStatus = curl_getinfo($oCurl);
	curl_close($oCurl);
	if(intval($aStatus["http_code"])==200){
		return $sContent;
	}else{
		return false;
	}
}
//带参数跳转到oauth2.php
function oatuh2Login(){
	if(!isset($_GET['state']))
	{
		header('Location:http://'.$_SERVER['HTTP_HOST'].'/oauth2.php?PHP_SELF='.PHPSELFVAR($_SERVER['PHP_SELF']).'&'.RepPostVar($_SERVER['QUERY_STRING']));
	}
}
//参数处理函数
function PHPSELFVAR($val,$ecms=0){
	if($ecms)
	{
		$val=str_replace("_","/",$val);
		$val=str_replace(" ","",$val);
		$val=str_replace("-",".",$val);
	}
	else
	{
		$val=str_replace("/","_",$val);
		$val=str_replace(" ","",$val);
		$val=str_replace(".","-",$val);
	}
	return $val;
}
//过滤用户昵称特殊字符
function deleteEmoji($str) {
	if($str){
		$tmpStr = json_encode($str);
		$tmpStr2 = preg_replace("#(\\\ud[0-9a-f]{3})#ie","",$tmpStr);
		$return = json_decode($tmpStr2);
		if(!$return){
			return deleteEmoji($return);
		}
	}else{
		$return = '';
	}    
	return $return;
}
//关键字处理
function Keyword($user){
	global $empire,$dbtbpre,$class_r,$WeiXin;
	$Content = str_replace(' ', '',trim($WeiXin->getRevContent()));
	wechatReplyText("此公众号没有绑定场馆");
}
//处理扫秒二维码
function QRCode($eventKey,$openid){
	global $empire,$options;
	if(strstr($eventKey, 'bindUid_'))//家长绑定学生
	{
		//wechatReplyText(whereSQL($options['student'],0,'id,newstime,tidName,openid')."id='$uid'");
		$uid=str_replace('bindUid_','',$eventKey);
		
		$r=$empire->fetch1(whereSQL($options['student'],0,'id,newstime,uidName,openid,openid1,keMu')."id='$uid'");
		if($r['id'])
		{
			$Field = 'openid';
			if($r['openid'])
			{
				$Field = 'openid1';
				if($r['openid1'])
				{
					$Field = 'openid';
				}
			}
			$empire->query(whereSQL($options['student'],2).$Field."='$openid' where id='$uid'");
			wechatReplyText("绑定成功\n姓名:".$r['uidName']."\n科目:".keMuTxt($r['keMu'])."\n时间:".date("Y-m-d H:i")."\n<a href=\"http://".$_SERVER['HTTP_HOST']."/webapp/?ac=jiazhang\">查看详情</a>");
		}
		else
		{
			wechatReplyText("二维码错误(".$eventKey.")");
		}
	}
	else if(strstr($eventKey, 'bindTid_'))//家长绑定教师
	{
		$tid=str_replace('bindTid_','',$eventKey);
		
		$r=$empire->fetch1(whereSQL($options['teacher'],0,'id,newstime,tidName,openid,keMu')."id='$tid'");
		if($r['id'])
		{
			$Field = 'openid';
			$empire->query(whereSQL($options['teacher'],2).$Field."='$openid' where id='$tid'");
			wechatReplyText("绑定成功\n姓名:".$r['tidName']."\n科目:".keMuTxt($r['keMu'])."\n时间:".date("Y-m-d H:i")."\n<a href=\"http://".$_SERVER['HTTP_HOST']."/webapp/\">查看详情</a>");
		}
		else
		{
			wechatReplyText("二维码错误(".$eventKey.")");
		}
	}
	else
	{
		wechatReplyText('扫带参数二维码(key:'.$eventKey.')');
	}
	
}
//回复消息
function wechatReplyText($text,$type=0,$openid=''){
	global $empire,$WeiXin;
	if($type&&$openid) //客服消息
	{
		$WeiXin->sendCustomMessage(array('touser'=>$openid,'msgtype'=>'text','text'=>array('content'=>$text)));
	}
	else
	{
		$text=$text?$text:'欢迎使用！';
		$WeiXin->text($text)->reply();
		db_close();
		$empire=null;
		exit;
	}
}
/* 
 * 回调 json
 * @param int   errCode   错误编码
 * @param int   errMsg    错误描述
 * @param int   close     0打印后关闭数据库 1回调return
 * @param array data      附件信息 array('tid'=>1,uid=>2,'tidName'=>'张三','uidName'=>'李四')
 * return HTML|JSON
 */
function wxErrorJson($errCode=1,$errMsg='系统错误',$close=0,$data=array()){
	global $empire;
	$data['errCode']=$errCode;
	$data['errMsg']=$errMsg;
	if(empty($close))
	{
		echo json_encode($data);
		db_close();
		$empire=null;
		exit();
	}
	return $data;
}
/* 
 * 回调 HTML
 * @param int    icon   0成功 1失败
 * @param sting  title  标题
 * @param sting  desc   描述
 * @param sting  btnText  按钮说明
 * @param sting  btnUrl   按钮链接
 * 成功 wxErrorHTML(1,'操作成功','内容详情，可根据实际需要安排','推荐操作','')
 * 失败 wxErrorHTML(0,'操作失败','内容详情，可根据实际需要安排','推荐操作','')
 *
 */
function wxErrorHTML($icon=0,$title='操作失败',$desc='',$btnText='',$btnUrl=''){
	@include(ECMS_PATH.'e/message/message.php');
	db_close();
	exit();
}

/* 
 * CURL方式操作帝国信息 增加、删除信息
 *
 * @param int   id        增加信息时id为空
 * @param int   classid   *目标栏目ID
 * @param sting enews     *操作类型AddNews增加、EditNews修改、DelNews删除（增加删除必须携带信息ID）
 								 MoveNews_all移动信息
 * @param int   userid    后台管理员ID
 * @param sting username  后台管理员名称
 * @param sting md5key    md5($userid.$username)
 * @param sting newspath  *信息目录
 * @param int   filename  *文件名（修改信息时必须带值）
 * @param sting curl_url  API接口地址（为空时自动识别当前域名）
 * @param sting title     *信息标题
 * 可携带其他远端可接收的自定义字段
 * return array("id"=>123,classid="123",title="我是标题")
 *
 	//增加
	$param = array();
	$param['classid'] = '64';
	$param['title'] = '111';
	$param['file'] = '111';
	$param['sid'] = '111';
	$param['curl_url'] = "http://yxttest.we0752.com/e/dede/ecmsinfo_curl.php";
	echo "<pre>";
	print_r(ECMS_Infor_Curl($param));
	echo "</pre>";
	//修改
	$param = array();
	$param['enews'] = 'EditNews';
	$param['classid'] = '64';
	$param['title'] = '111';
	$param['newspath'] = '111';
	$param['filename'] = '111';
	echo "<pre>";
	print_r(ECMS_Infor_Curl($param));
	echo "</pre>";

 *
 */
function ECMS_Infor_Curl($param,$ecms=0){
	$Var   = PostInfoVar($param,$ecms);
	$param = array_merge($param,$Var);

	$http_post_data = http_post($param['curl_url'],$param);
	$http_post_data_json = json_decode($http_post_data,true);
	if(empty($http_post_data_json))
	{
		$http_post_data_r = explode("<b>",$http_post_data);
		$http_post_data_r = explode("</b>",$http_post_data_r[1]);
		$http_post_data_json = array("state" => $http_post_data_r[0]);
		if(empty($http_post_data_r[0]))
		{
			$http_post_data_json = array("state" => $http_post_data);
		}
	}
	else
	{
		$http_post_data_json['state'] = "成功";
	}
	return $http_post_data_json;
}
//系统字段
function PostInfoVar($param,$ecms=0){
	$param['md5cdk']   = "lkSDj90835lk2LLKJS00AA";
	$param['md5key']   = md5($param['md5cdk']);
	$param['curl_url'] = $param['curl_url']?$param['curl_url']:"http://".$_SERVER['HTTP_HOST']."/e/admin/ecmsinfo_curl.php";
	if(!$ecms) //信息
	{
		$param['id']       = $param['id']?$param['id']:"";
		$param['classid']  = (int)$param['classid'];
		$param['infoip']   = "infoip";
		$param['newstime'] = $param['newstime']?$param['newstime']:time();
		$param['newstime'] = date("Y-m-d H:i:s",$param['newstime']);
		$param['enews']    = $param['enews']?$param['enews']:"AddNews";
		$param['userid']   = $param['userid']?$param['userid']:1;
		$param['username'] = $param['username']?$param['username']:"admin";
		$param['ismember'] = $param['ismember']?1:0; //1为前台会员发布，0为后台发布
		$param['checked']  = $param['check']==1?0:1;
		$param['newspath'] = $param['newspath']?$param['newspath']:date("Y-m-d");
		$param['filename'] = $param['enews']=="EditNews"?$param['filename']:"";		
	}
	else if($ecms==1)
	{
		$param['curl_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/e/member/doaction_curl.php';
	}
	return $param;
}

/**
 * 生成select和tbanme
 * @param int    $classid  栏目ID
 * @return boolean|string
 */
function tbname($classid){
	global $class_r;
	$tbname = $class_r[$classid]['tbname'];
	if(!$tbname) wxErrorJson(40004,'tbname空，classid('.$classid.')'); 
	return $tbname;
}
/**
 * 生成select SQL
 * @param int    $classid  栏目ID
 * @param int    $ecms     0查询SQL、1统计SQL、2更新SQL
 * @param string $field    字段名称 'id,title'
 * @return boolean|string
 */
function whereSQL($classid,$ecms=0,$field='*'){
	global $dbtbpre;
	$tbname = tbname($classid);
	if(!$tbname) wxErrorJson(40003,'tbname空'); 
	if($ecms==1)
	{
		return "select count(*) as total from {$dbtbpre}ecms_$tbname where ";
	}
	else if($ecms==2)
	{
		return "update {$dbtbpre}ecms_$tbname set ";
	}
	else
	{
		return "select $field from {$dbtbpre}ecms_$tbname where ";
	}
}
//检测学员身份
function checkStudent($uid){
	global $empire,$options;
	$r=$empire->fetch1(whereSQL($options['student'],0,'id,title,newstime,tidName,uidName,keMu,openid')."id='$uid'");
	if($r['id'])
	{
		
		return wxErrorJson(0,'success',1,array('id'=>$r['id'],'uid'=>$r['id'],'uidName'=>$r['uidName'],'title'=>$r['title'],'newstime'=>$r['newstime'],'keMu'=>$r['keMu'],'keMuTxt'=>keMuTxt($r['keMu']),'openid'=>$r['openid']));
	}
	else
	{
		wxErrorJson(40004,'非学员身份，请联系客服申请'); 
	}
}
//检测教员身份
function checkTeacher($openid){
	global $empire,$options;
	$r=$empire->fetch1(whereSQL($options['teacher'],0,'id,title,newstime,tidName,keMu,openid')."openid='$openid'");
	if($r['id'])
	{
		$kuMuArr=array('钢琴','吉他');
		//return wxErrorJson(0,'教员身份确认成功',$r);
		return wxErrorJson(0,'success',1,array('id'=>$r['id'],'tid'=>$r['id'],'tidName'=>$r['tidName'],'title'=>$r['title'],'openid'=>$r['openid'],'newstime'=>$r['newstime'],'keMu'=>$r['keMu'],'keMuTxt'=>keMuTxt($r['keMu'])));
	}
	else
	{
		wxErrorJson(40004,'非教员身份，请联系客服申请'); 
	}
}
//教师绑定的学生人数
function teacherBindStudentNum($tid){
	global $empire,$options;
	$num=$empire->gettotal(whereSQL($options['student'],1)."tid='$tid'");
	return (int)$num;
}
//教师、学员、系统上课次数
function shangKeNum($tid=0,$uid=0){
	global $empire,$options;
	if($tid)
	{
		$where = "tid='$tid'";
	}
	else if($uid)
	{
		$where = "uid='$uid'";
	}
	else
	{
		$where = '';
	}
	$num=$empire->gettotal(whereSQL($options['log2'],1).$where);
	return (int)$num;
}
//教师、学员、系统充值数量
function chongZhiNum($tid=0,$uid=0){
	global $empire,$options;
	if($tid)
	{
		$where = "tid='$tid'";
	}
	else if($uid)
	{
		$where = "uid='$uid'";
	}
	else
	{
		$where = '';
	}
	$r=$empire->fetch1(whereSQL($options['log1'],0,'sum(num) as num').$where);
	return (int)$r['num'];
}
//获取星星数量
function getStarNum($tid=0,$uid=0){
	global $empire,$options;
	if($tid)
	{
		$where = "tid='$tid'";
	}
	else if($uid)
	{
		$where = "uid='$uid'";
	}
	else
	{
		$where = '';
	}
	$r=$empire->fetch1(whereSQL($options['log2'],0,'sum(num) as num').$where);
	return (int)$r['num'];
}
//生成学员二维码
function getStudentQR($id){
	global $empire,$options,$WeiXin;
	if(!$id) return false;
	$scene_id = "bindUid_".$id;
	$res=$WeiXin->getQRCode($scene_id,2);
	if($res!==false) {
		$empire->query(whereSQL($options['student'],2)."QRurl='$res[url]',QRkey='$res[ticket]' where id='$id'");
		return $res['ticket'];
	}
	return false;
}
//生成教师二维码
function getTeacherQR($id){
	global $empire,$options,$WeiXin;
	if(!$id) return false;
	$scene_id = "bindTid_".$id;
	$res=$WeiXin->getQRCode($scene_id,2);
	if($res!==false) {
		$empire->query(whereSQL($options['teacher'],2)."QRurl='$res[url]',QRkey='$res[ticket]' where id='$id'");
		return $res['ticket'];
	}
	return false;
}
//返回科目
function keMuTxt($keMu){
	$keMuArr=array('钢琴','吉他');
	return $keMuArr[$keMu];
}
//返回周几
function week($week){
	$weekArr = array('日','一','二','三','四','五','六');
	return $weekArr[$week];
}

function getWeekSend($week,$next=0){
	//$unixTime = strtotime("2017-09-24");
	if($next)
	{
		$nextTime = strtotime("next Monday");
		$nextDate = date('Y-m-d',$nextTime);
		if($week==0) $week=7;
		return date("Y-m-d",$nextTime+84600*($week-2));
	}
	$unixTime = time();
	$w = date("w",$unixTime);
	if($week==$w)
	{
		return date("Y-m-d",$unixTime);
	}
	else if($week==0||$week>$w)
	{
		if($week==0) $week=7;
		return date("Y-m-d",$unixTime+84600*($week-$w-1));
	}
	else if($w==0||$week<$w)
	{
		$nextTime = strtotime("next Monday");
		$nextDate = date('Y-m-d',$nextTime);
		if($week==0)
		{
			$week=7;
		}
		return date("Y-m-d",$nextTime+84600*($week-2));
	}
	else
	{
		echo 'err';
	}
}

/**
 * 组建模板消息数据
 * @param string $touser
 * @param string $tempid
 * @param string $url
 * @param array $array
 * @param array $color 参数颜色
 * $array数组结构:
 *   array(
 *  	"first"=>"您好，这是标题",
 *  	"remark"=>"备注说明",
 *  	"字段"=>....
 *   )
 */
function sendTemplateMessage_date($touser,$tempid,$url,$array,$color=array()){
	$keys = array_keys($array);
	$arrNew = array();
	foreach($keys as $val)
	{
		//$arrNew[$val]['value'] = urlencode($array[$val]);
		$arrNew[$val]['value'] = $array[$val];
		$arrNew[$val]['color'] = $color[$val]?$color[$val]:"#173177";
	}
	$data = array();
	$data['touser'] = $touser;
	$data['template_id'] = $tempid;
	$data['url'] = $url;
	$data['topcolor'] = "#5cb85c";
	$data['data'] = array();
	$data['data']=$arrNew;
	return $data;
}

